/**
 * TableDetailPage
 * 表元数据详情页面
 * Features: 表基本信息、字段列表、主键/外键标识
 */

import React from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { Card, Descriptions, Table, Button, Tag, Space, Empty } from 'antd'
import { ArrowLeftOutlined, KeyOutlined, LinkOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import { useTableDetail, useTableColumns } from '@/hooks/useMetadata'
import type { MetadataColumn } from '@/services/models/types'
import { TableType } from '@/services/models/types'

const TABLE_TYPE_CONFIG: Record<TableType, { color: string; text: string }> = {
  [TableType.TABLE]: { color: 'blue', text: '表' },
  [TableType.VIEW]: { color: 'cyan', text: '视图' },
  [TableType.MATERIALIZED_VIEW]: { color: 'purple', text: '物化视图' },
}

export const TableDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()

  // 查询表详情和字段列表
  const { data: table, isLoading: tableLoading } = useTableDetail(Number(id))
  const { data: columns = [], isLoading: columnsLoading } = useTableColumns(Number(id))

  const isLoading = tableLoading || columnsLoading

  if (isLoading) {
    return <div className="p-6">加载中...</div>
  }

  if (!table) {
    return (
      <div className="p-6">
        <Empty description="表不存在" />
        <Button onClick={() => navigate('/metadata')} className="mt-4">
          返回搜索
        </Button>
      </div>
    )
  }

  const tableTypeConfig = TABLE_TYPE_CONFIG[table.tableType]

  // 字段列表表格列定义
  const columnColumns: ColumnsType<MetadataColumn> = [
    {
      title: '序号',
      dataIndex: 'ordinalPosition',
      width: 80,
      align: 'center',
    },
    {
      title: '字段名',
      dataIndex: 'columnName',
      width: 200,
      render: (columnName, record) => (
        <Space>
          <span className="font-mono">{columnName}</span>
          {record.isPrimaryKey && (
            <Tag icon={<KeyOutlined />} color="gold">
              PK
            </Tag>
          )}
          {record.isForeignKey && (
            <Tag icon={<LinkOutlined />} color="purple">
              FK
            </Tag>
          )}
        </Space>
      ),
    },
    {
      title: '数据类型',
      dataIndex: 'dataType',
      width: 150,
      render: (dataType, record) => {
        let typeStr = dataType
        if (record.columnSize) {
          typeStr += `(${record.columnSize}`
          if (record.decimalDigits) {
            typeStr += `,${record.decimalDigits}`
          }
          typeStr += ')'
        }
        return <span className="font-mono text-blue-600">{typeStr}</span>
      },
    },
    {
      title: '可空',
      dataIndex: 'nullable',
      width: 100,
      align: 'center',
      render: (nullable) =>
        nullable ? (
          <CheckCircleOutlined className="text-green-500" />
        ) : (
          <CloseCircleOutlined className="text-red-500" />
        ),
    },
    {
      title: '默认值',
      dataIndex: 'defaultValue',
      width: 150,
      render: (defaultValue) => (defaultValue ? <span className="font-mono">{defaultValue}</span> : '-'),
    },
    {
      title: '注释',
      dataIndex: 'columnComment',
      ellipsis: true,
      render: (comment) => comment || '-',
    },
  ]

  // 统计主键和外键数量
  const primaryKeyCount = columns.filter((col) => col.isPrimaryKey).length
  const foreignKeyCount = columns.filter((col) => col.isForeignKey).length

  return (
    <div className="p-6">
      <div className="mb-4 flex justify-between items-center">
        <Space>
          <Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/metadata')}>
            返回搜索
          </Button>
          <h1 className="text-2xl font-bold">
            {table.schemaName ? `${table.schemaName}.${table.tableName}` : table.tableName}
          </h1>
        </Space>
      </div>

      <Space direction="vertical" size="large" className="w-full">
        {/* 表基本信息 */}
        <Card title="表基本信息">
          <Descriptions column={2} bordered>
            <Descriptions.Item label="表名">{table.tableName}</Descriptions.Item>
            <Descriptions.Item label="Schema">{table.schemaName || '-'}</Descriptions.Item>

            <Descriptions.Item label="表类型">
              <Tag color={tableTypeConfig.color}>{tableTypeConfig.text}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="数据源">
              <Space>
                <span>{table.datasourceName}</span>
                <Tag>{table.datasourceStatus}</Tag>
              </Space>
            </Descriptions.Item>

            <Descriptions.Item label="行数">
              {table.rowCount ? table.rowCount.toLocaleString() : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="大小">
              {table.sizeInBytes
                ? table.sizeInBytes < 1024 * 1024
                  ? `${(table.sizeInBytes / 1024).toFixed(2)} KB`
                  : table.sizeInBytes < 1024 * 1024 * 1024
                  ? `${(table.sizeInBytes / (1024 * 1024)).toFixed(2)} MB`
                  : `${(table.sizeInBytes / (1024 * 1024 * 1024)).toFixed(2)} GB`
                : '-'}
            </Descriptions.Item>

            <Descriptions.Item label="创建时间">{table.createdAt}</Descriptions.Item>
            <Descriptions.Item label="更新时间">{table.updatedAt}</Descriptions.Item>

            <Descriptions.Item label="表注释" span={2}>
              {table.tableComment || '-'}
            </Descriptions.Item>
          </Descriptions>
        </Card>

        {/* 字段列表 */}
        <Card
          title={
            <Space>
              <span>字段列表 ({columns.length} 个字段)</span>
              {primaryKeyCount > 0 && (
                <Tag icon={<KeyOutlined />} color="gold">
                  {primaryKeyCount} 个主键
                </Tag>
              )}
              {foreignKeyCount > 0 && (
                <Tag icon={<LinkOutlined />} color="purple">
                  {foreignKeyCount} 个外键
                </Tag>
              )}
            </Space>
          }
        >
          <Table
            columns={columnColumns}
            dataSource={columns}
            rowKey="id"
            pagination={false}
            scroll={{ x: 1000 }}
          />
        </Card>
      </Space>
    </div>
  )
}

export default TableDetailPage
